<template>
	<div class="game-container report-container">
		<div class="view-container dealer-container">
			<div class="params">
				<el-form ref="searchForm" :inline="true" :model="queryData">
					<el-form-item class="time-options">
						<el-select
							v-model="timeOptions"
							:placeholder="$t('common.please_choose')"
							style="width:150px;margin-right: -3px;"
						>
							<el-option label="到账时间" value="1"></el-option>
							<el-option
								:label="`${$t('funds.apply_time')}:`"
								value="2"
							></el-option>
						</el-select>

						<el-date-picker
							v-model="searchTime"
							size="medium"
							:picker-options="pickerOptions"
							format="yyyy-MM-dd HH:mm:ss"
							type="datetimerange"
							range-separator="-"
							:start-placeholder="$t('common.start_date')"
							:end-placeholder="$t('common.end_date')"
							align="right"
							:clearable="false"
							:default-time="defaultTime"
							style="width: 375px"
							class="time-options-value"
						></el-date-picker>
					</el-form-item>

					<!-- <el-form-item label="存款时间:" prop="paymentAt">
						<el-date-picker
							v-model="queryData.paymentAt"
							type="datetimerange"
							size="medium"
							:start-placeholder="$t('common.start_date')"
							:end-placeholder="$t('common.end_date')"
							:picker-options="pickerOptions"
							:default-time="defaultTime"
							value-format="timestamp"
							clearable
							align="right"
						></el-date-picker>
					</el-form-item> -->
					<el-form-item
						:label="`${$t('funds.order_no')}:`"
						prop="orderNo"
					>
						<el-input
							v-model.trim="queryData.orderNo"
							style="width: 305px"
							:placeholder="$t('common.please_enter')"
							clearable
						></el-input>
					</el-form-item>
					<el-form-item label="申请账号:" prop="applyAccount">
						<el-input
							v-model.trim="queryData.applyAccount"
							:placeholder="$t('common.please_enter')"
							style="width: 230px"
							maxlength="11"
							clearable
						></el-input>
					</el-form-item>
					<el-form-item
						:label="`${$t('funds.user_name')}:`"
						prop="memberAccount"
					>
						<el-input
							v-model.trim="queryData.memberAccount"
							:placeholder="$t('common.please_enter')"
							style="width: 230px"
							maxlength="11"
							clearable
						></el-input>
					</el-form-item>
					<el-form-item label="会员姓名:" prop="memberName">
						<el-input
							v-model.trim="queryData.memberName"
							:placeholder="$t('common.please_enter')"
							style="width: 210px"
							maxlength="15"
							clearable
						></el-input>
					</el-form-item>
					<el-form-item label="订单来源:" prop="applySource">
						<el-select
							v-model="queryData.applySource"
							:placeholder="$t('common.select_all')"
							clearable
						>
							<el-option
								v-for="item in applySourceArr"
								:key="item.code"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item
						:label="`${$t('funds.fund_audit.order_status')}:`"
						prop="orderStatus"
					>
						<el-select
							v-model="queryData.orderStatus"
							:placeholder="$t('common.select_all')"
							clearable
						>
							<el-option
								v-for="item in orderStatusArr"
								:key="item.code"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="支付方式:" prop="payType">
						<el-select
							v-model="queryData.payType"
							:placeholder="$t('common.select_all')"
							style="width: 231px"
							clearable
						>
							<el-option
								v-for="item in rechargeMethods"
								:key="item.code"
								:label="item.value"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="存款金额:">
						<el-input-number
							v-model="queryData.depositAmountStart"
							:placeholder="$t('common.minimum')"
							style="width: 150px"
							size="medium"
							:min="1"
							:max="99999999999"
							:precision="2"
							:controls="false"
						></el-input-number>
						-
						<el-input-number
							v-model="queryData.depositAmountEnd"
							:placeholder="$t('common.maximum')"
							style="width: 150px"
							size="medium"
							:min="queryData.depositAmountStart"
							:max="99999999999"
							:precision="2"
							:controls="false"
						></el-input-number>
					</el-form-item>
					<el-form-item label="操作人:" prop="createdBy">
						<el-input
							v-model.trim="queryData.createdBy"
							:placeholder="$t('common.please_enter')"
							style="width: 210px"
							maxlength="11"
							clearable
						></el-input>
					</el-form-item>
					<el-form-item label="VIP等级:">
						<el-input
							v-model="queryData.minVipSerialNum"
							size="medium"
							:placeholder="$t('common.minimum')"
							style="width: 133px"
							maxlength="3"
							name="minVipSerialNum"
							oninput="value=value.replace(/[^\d]/g,'')"
							@blur="checkValue($event)"
						></el-input>
						-
						<el-input
							v-model="queryData.maxVipSerialNum"
							size="medium"
							:placeholder="$t('common.maximum')"
							style="width: 133px"
							maxlength="3"
							oninput="value=value.replace(/[^\d]/g,'')"
							name="maxVipSerialNum"
							@blur="checkValue($event)"
						></el-input>
					</el-form-item>
					<el-form-item label="使用站点:" class="tagheight">
						<el-select
							v-model="queryData.loginAppId"
							clearable
							:placeholder="$t('common.select_all')"
							:popper-append-to-body="false"
						>
							<el-option
								v-for="item in appId"
								:key="item.code"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item style="margin-left: 8px">
						<el-button
							type="primary"
							icon="el-icon-search"
							:disabled="loading"
							size="medium"
							@click="search"
						>
							查询
						</el-button>
						<el-button
							icon="el-icon-refresh-left"
							:disabled="loading"
							size="medium"
							@click="reset"
						>
							重置
						</el-button>
						<el-button
							v-if="hasPermission('604')"
							type="warning"
							icon="el-icon-folder-add"
							size="medium"
							:disabled="loading"
							@click="exportExcel"
						>
							导出
						</el-button>
					</el-form-item>
					<el-form-item
						:label="`${$t('funds.fund_audit.order_status')}:`"
					></el-form-item>
				</el-form>
			</div>
			<div class="content">
				<el-table
					v-loading="loading"
					element-loading-spinner="el-icon-loading"
					border
					size="mini"
					:data="tableData"
					style="width: 100%"
					show-summary
					:summary-method="getSummaries"
					:header-cell-style="getRowClass"
					@sort-change="_changeTableSort"
				>
					<el-table-column
						prop="orderNo"
						align="center"
						:label="$t('funds.order_no')"
						min-width="200px"
					>
						<template slot-scope="scope">
							<Copy
								v-if="scope.row.orderNo"
								:title="scope.row.orderNo"
								:copy="copy"
							/>
							<span v-else>-</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="loginAppId"
						align="center"
						label="使用站点"
						min-width="90"
					>
						<template slot-scope="scope">
							{{ typeFilter(scope.row.loginAppId, 'appId') }}
						</template>
					</el-table-column>

					<el-table-column
						prop="memberAccount"
						align="center"
						:label="$t('funds.user_name')"
						min-width="160px"
					>
						<template slot-scope="scope">
							<Copy
								v-if="scope.row.memberAccount"
								:title="scope.row.memberAccount"
								:copy="copy"
							/>
							<span v-else>-</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="vipGrade"
						align="center"
						:label="$t('funds.vip_level')"
						min-width="130"
						sortable="custom"
					>
						<template slot-scope="scope">
							{{
								scope.row.vipGrade || scope.row.vipGrade === 0
									? 'VIP' + scope.row.vipGrade
									: '-'
							}}
						</template>
					</el-table-column>
					<el-table-column
						prop="memberName"
						align="center"
						:label="$t('funds.fund_audit.real_name')"
						min-width="130px"
					>
						<template slot-scope="scope">
							<Copy
								v-if="scope.row.memberName"
								:title="scope.row.memberName"
								:copy="copy"
							/>
							<span v-else>-</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="applySource"
						align="center"
						:label="$t('funds.fund_audit.app_type')"
						min-width="130px"
					>
						<template slot-scope="scope">
							<span>
								{{
									typeFilter(
										scope.row.applySource,
										'loginDeviceType'
									)
								}}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="orderStatus"
						align="center"
						:label="$t('funds.fund_audit.order_status')"
						min-width="110px"
					>
						<template slot-scope="scope">
							<span
								v-if="
									scope.row.orderStatus ||
										scope.row.orderStatus === 0
								"
								:class="
									scope.row.orderStatus === 1
										? 'lockingRgba'
										: scope.row.orderStatus === 0
										? 'normalRgba'
										: 'deleteRgba'
								"
							>
								{{
									typeFilter(
										scope.row.orderStatus,
										'valetPayStatus'
									)
								}}
							</span>
							<span v-else>-</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="payType"
						align="center"
						label="支付方式"
						min-width="120px"
					>
						<template slot-scope="scope">
							<span>
								{{ filterRechargeMethod(scope.row.payType) }}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="depositorName"
						align="center"
						label="存款人姓名"
						min-width="120px"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.depositorName || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="depositAmount"
						align="center"
						label="存款金额"
						sortable="custom"
						min-width="160px"
					>
						<template slot-scope="scope">
							<span>
								{{ decimalToFixed2(scope.row.depositAmount) }}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="actualAmountReceived"
						align="center"
						label="实际到账金额"
						sortable="custom"
						min-width="160px"
					>
						<template slot-scope="scope">
							<span>
								{{
									decimalToFixed2(
										scope.row.actualAmountReceived
									)
								}}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="applyAt"
						align="center"
						:label="`${$t('funds.apply_time')}:`"
						sortable="custom"
						min-width="160px"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.applyAt || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="depositAt"
						align="center"
						label="到账时间"
						sortable="custom"
						min-width="160px"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.depositAt || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="applyAccount"
						align="center"
						label="申请账号"
						min-width="160px"
					>
						<template slot-scope="scope">
							<Copy
								v-if="scope.row.applyAccount"
								:title="scope.row.applyAccount"
								:copy="copy"
							/>
							<span v-else>-</span>
						</template>
					</el-table-column>

					<el-table-column
						prop="creditLevel"
						align="center"
						label="信用等级"
						min-width="120px"
					>
						<template slot-scope="scope">
							<span>
								{{ getNumberValue(scope.row.creditLevel) }}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="createdBy"
						align="center"
						label="操作人"
						min-width="120px"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.createdBy || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="remark"
						align="center"
						:label="$t('common.remark')"
						min-width="200px"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.remark || '-' }}</span>
						</template>
					</el-table-column>
				</el-table>

				<!-- 分页 -->
				<el-pagination
					:current-page.sync="pageNum"
					class="pageValue"
					background
					layout="total, sizes,prev, pager, next, jumper"
					:page-size="pageSize"
					:page-sizes="pageSizes"
					:total="total"
					@current-change="handleCurrentChange"
					@size-change="handleSizeChange"
				></el-pagination>
			</div>
		</div>
	</div>
</template>

<script>
import list from '@/mixins/list'
import { routerNames } from '@/utils/consts'
import dayjs from 'dayjs'

const start = dayjs()
	.startOf('day')
	.subtract(6, 'd')

const end = dayjs()
	.endOf('day')
	.valueOf()

export default {
	name: routerNames.valetRechargeRecord,
	mixins: [list],
	data() {
		return {
			tableData: [],
			loading: false,
			summary: {},
			rechargeMethods: [],
			timeOptions: '1',
			searchTime: [start, end],
			queryData: {
				// paymentAt: [start, end],
				applyAccount: undefined,
				applySource: undefined,
				createdBy: undefined,
				depositAmountEnd: undefined,
				depositAmountStart: undefined,
				memberAccount: undefined,
				memberName: undefined,
				orderNo: undefined,
				orderStatus: undefined,
				payType: undefined,
				orderKey: undefined,
				orderType: undefined,
				minVipSerialNum: undefined,
				maxVipSerialNum: undefined
			}
		}
	},
	computed: {
		appId() {
			return this.globalDics.appId || []
		},
		applySourceArr() {
			return this.$store.getters.globalDics.loginDeviceType || []
		},
		orderStatusArr() {
			return this.$store.getters.globalDics.valetPayStatus || []
		}
	},
	watch: {
		'queryData.depositAmountStart'(val) {
			if (
				this.queryData.depositAmountStart >
				this.queryData.depositAmountEnd
			) {
				this.queryData.depositAmountEnd =
					this.queryData.depositAmountStart + 0.01
			}
		}
	},
	created() {
		this.getkvconfigList()
	},
	methods: {
		filterRechargeMethod(code) {
			const item = this.rechargeMethods.find(
				(item) => item.code === String(code)
			)
			return item ? item.value : '-'
		},
		// 字典查询代客充值方式
		getkvconfigList() {
			const params = {
				k: 'recharge.type.config',
				...this.getParams()
			}
			this.$api
				.getkvconfigQueryList(params)
				.then((res) => {
					// 返回数组字符串或json字符串
					const str = res.data.records[0].v
					const obj = JSON.parse(str)
					// this.rechargeMethods = JSON.parse(json)
					for (const i in obj) {
						this.rechargeMethods.push({ code: i, value: obj[i] })
					}
				})
				.catch(() => {
					this.loading = false
				})
		},
		loadData() {
			this.loading = true
			const [startTime, endTime] = this.searchTime || []
			const obj = {
				'1': 'deposit',
				'2': 'create'
			}
			const params = {
				[obj[this.timeOptions] + 'StartAt']: startTime
					? dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				[obj[this.timeOptions] + 'EndAt']: endTime
					? dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				...this.getParams(this.queryData)
			}
			delete params.paymentAt
			this.$api
				.getValetRechargeRecordList(params)
				.then((res) => {
					const { record, totalRecord, summary } = res.data || {}
					this.tableData = Array.isArray(record)
						? Object.freeze(record)
						: []
					this.total = totalRecord || 0
					this.summary = summary || {}
					this.loading = false
				})
				.catch(() => {
					this.loading = false
				})
		},
		reset() {
			this.$refs['searchForm'].resetFields()
			this.searchTime = [start, end]
			this.queryData = {}
			this.timeOptions = '1'
			this.pageNum = 1
			this.queryData.depositAmountEnd = undefined
			this.queryData.depositAmountStart = undefined
			this.loadData()
		},
		_changeTableSort({ column, prop, order }) {
			// 排序列(1)：1-存款金额 2-到账金额 3-存款时间
			const keyMap = new Map([
				['depositAmount', 1],
				['actualAmountReceived', 2],
				['depositAt', 3],
				['applyAt', 4],
				['vipGrade', 5]
			])
			this.pageNum = 1
			this.queryData.orderKey = order ? keyMap.get(prop) : undefined
			order === 'ascending' && (this.queryData.orderType = 'asc')
			order === 'descending' && (this.queryData.orderType = 'desc')
			!order && (this.queryData.orderType = undefined)
			this.loadData()
		},
		getSummaries(param) {
			const { columns } = param
			const sums = []
			columns.forEach((column, index) => {
				if (index === 0) {
					const el = (
						<div class='count_row'>
							<p>小计</p>
							<p>合计</p>
						</div>
					)
					sums[index] = el
					return
				} else if (index === 8) {
					const el = (
						<div class='count_row'>
							<p>
								{this.decimalToFixed2(
									this.summary.amountSubtotal
								)}
							</p>
							<p>
								{this.decimalToFixed2(this.summary.amountTotal)}
							</p>
						</div>
					)
					sums[index] = el
					return
				} else if (index === 9) {
					const el = (
						<div class='count_row'>
							<p>
								{this.decimalToFixed2(
									this.summary.actualAmountSubtotal
								)}
							</p>
							<p>
								{this.decimalToFixed2(
									this.summary.actualAmountTotal
								)}
							</p>
						</div>
					)
					sums[index] = el
					return
				}
			})

			return sums
		},
		checkValue(e) {
			const { name, value } = e.target
			switch (name) {
				case 'minVipSerialNum':
					if (
						!!this.queryData.maxVipSerialNum &&
						value &&
						value * 1 > this.queryData.maxVipSerialNum * 1
					) {
						this.$message({
							type: 'warning',
							message: `VIP等级最小值不能大于最大值`
						})
						this.queryData.minVipSerialNum = undefined
					} else {
						this.queryData.minVipSerialNum = value
					}
					break
				case 'maxVipSerialNum':
					if (
						!!this.queryData.minVipSerialNum &&
						value &&
						value * 1 < this.queryData.minVipSerialNum * 1
					) {
						this.$message({
							type: 'warning',
							message: `VIP等级最大值不能小于最小值`
						})
						this.queryData.maxVipSerialNum = undefined
					} else {
						this.queryData.maxVipSerialNum = value
					}
					break
			}
		},
		exportExcel() {
			const [startTime, endTime] = this.searchTime || []
			const obj = {
				'1': 'deposit',
				'2': 'create'
			}
			const params = {
				[obj[this.timeOptions] + 'StartAt']: startTime
					? dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				[obj[this.timeOptions] + 'EndAt']: endTime
					? dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				...this.getParams(this.queryData)
			}
			delete params.paymentAt
			this.$confirm(
				`<strong>${this.$t(
					'common.is_export'
				)}</strong></br><span style='font-size:12px;color:#c1c1c1'>${this.$t(
					'common.excess_data'
				)}</span>`,
				this.$t('common.success_tip'),
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: this.$t('common.confirm'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning'
				}
			)
				.then(() => {
					this.loading = true
					this.$api
						.valetRechargeDownloadAPI(params)
						.then((res) => {
							const { data, status } = res
							if (res && status === 200) {
								this.loading = false
								const { type } = data
								if (type.includes('application/json')) {
									const reader = new FileReader()
									reader.onload = (evt) => {
										if (evt.target.readyState === 2) {
											const {
												target: { result }
											} = evt
											const ret = JSON.parse(result)
											if (ret.code !== 200) {
												this.$message({
													type: 'error',
													message: ret.msg,
													duration: 1500
												})
											}
										}
									}
									reader.readAsText(data)
								} else {
									const result = res.data
									const disposition =
										res.headers['content-disposition']
									const fileNames =
										disposition && disposition.split("''")
									let fileName = fileNames[1]
									fileName = decodeURIComponent(fileName)
									const blob = new Blob([result], {
										type: 'application/octet-stream'
									})
									if (
										'download' in
										document.createElement('a')
									) {
										const downloadLink = document.createElement(
											'a'
										)
										downloadLink.download = fileName || ''
										downloadLink.style.display = 'none'
										downloadLink.href = URL.createObjectURL(
											blob
										)
										document.body.appendChild(downloadLink)
										downloadLink.click()
										URL.revokeObjectURL(downloadLink.href)
										document.body.removeChild(downloadLink)
									} else {
										window.navigator.msSaveBlob(
											blob,
											fileName
										)
									}
									this.$message({
										type: 'success',
										message: this.$t(
											'common.export_success'
										),
										duration: 1500
									})
								}
							}
						})
						.catch(() => {
							this.loading = false
							this.$message({
								type: 'error',
								message: '导出失败',
								duration: 1500
							})
						})
				})
				.catch(() => {})
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__title {
	font-weight: 600;
	color: #000000c2;
}

.view-container {
	display: flex;
	justify-content: flex-start;
	flex-direction: column;
}
.count_row {
	height: 80px;
	p {
		height: 40px;
		line-height: 40px;
		color: #5c5c5c;
		font-weight: 700;
		span {
			display: inline-block;
			width: 20px;
			height: 20px;
		}
	}
}
</style>
